package org.fluidripple.file;


import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;

@Configuration
@EnableScheduling
public class ClearFileScheduled {

    //每隔10小时执行一次
    @Scheduled(cron = "0 0 */10 * * ?")
    public void scheduledTask() {
        Path path = Paths.get(DeviceDataMappedFile.baseDirPath);
        if (Files.exists(path)){
            try {
                //获取设备目录
                Stream<Path> list = Files.list(path);
                list.forEach(deviceDir -> {
                    //如果是目录(设备编号目录)
                    if (Files.isDirectory(deviceDir)) {
                        try {
                            Stream<Path> files = Files.list(deviceDir);
                            files.forEach(filePath -> {
                                File file = filePath.toFile();
                                long diff = System.currentTimeMillis() - file.lastModified();
                                if ((diff/(24*60*60*1000))>=7) {
                                    //删除文件
                                    try {
                                        Files.delete(filePath);
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                }
                            });
                        } catch (IOException e) {
                           e.printStackTrace();
                        }
                    }
                });
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
